package com.solvePlat.config;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //用于存储客户端的连接
    private static ChannelGroup channelGroups = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);



    //当前有客户端连接时,,那么将连上的客户端记录下来
    //用户一旦刷新页面,
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel inComming = ctx.channel();
        //进入聊天室
        for(Channel ch:channelGroups){
            if (ch != inComming){
                ch.writeAndFlush("欢迎"+inComming.remoteAddress()+"进入聊天室");
            }
        }
        channelGroups.add(inComming);

        //首先判断当前用户的消息队列是否存在

        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("456");
        Channel inComming = ctx.channel();

        //进入聊天室
        for(Channel ch:channelGroups){
            if (ch != inComming){
                ch.writeAndFlush("再见"+inComming.remoteAddress()+"离开聊天室");
            }
        }



        channelGroups.remove(inComming);
        super.handlerRemoved(ctx);
    }

    //redis中将当前的channelid与用户uuid对应起来,
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        System.out.println("789");
        Channel incoming = channelHandlerContext.channel();

        //检查对应的channelid存在不存在,直接发送数据,不存在将该数据发送到消息队列中,订阅模式,
        //如何把消息发送到指定人,将当前用户的管道id保存到数据库中,如果当前用户处于离线,将该消息发送到消息队列当中,当用户登录的时候去订阅当前
        //根据传输过来的数据类型,进行判断当前是聊天信息,还是其他的推送通知
        //我说的时候把 id带上,目标 id 从哪里获取?,登录后的id存储在用户表中

        for(Channel ch:channelGroups){
            if (ch != incoming){
                ch.writeAndFlush(new TextWebSocketFrame("用户说"+textWebSocketFrame.text()));
            }else{
                ch.writeAndFlush(new TextWebSocketFrame("我说"+textWebSocketFrame.text()));
            }
        }
    }
}
